<?php
namespace app\admin\controller;

use think\Log;
use think\Db;
use think\Config;
use Wx\Wxpay\WxPaysdk;

class Order extends Base
{
    public function index()
    {
        $keywords = request()->get('keywords');
        $sort = Request()->get('pay_time')?Request()->get('pay_time'):"order_status asc,pay_time desc";
        $this->assign('sort',$sort);

        $order_status=request()->param('order_status');
        $order_id = input('order_id');
        
        if (empty($order_status) || $order_status == 1000) {
			if($keywords){
				$where = ['order_no|receiver_name|receiver_mobile|receiver_pcd|receiver_address' => ['like','%'.$keywords.'%'],'order_status' => ['>',0]];
			}else{
				$where = ['order_status' => ['in','20,25,30,40']];           //['order_status' => 20];
			}
        } else {
            if ($order_id) {
                $info = db('order')->where('order_id', $order_id)->find();
                if ($info['order_status']!=20) {
                    $this->success('订单已被接');
                }
                Db::startTrans();
                $res = db::name('order')->update(['order_id' => $order_id,'order_status' => $order_status]);
                if ($res !== false) {
                    $goods = db::name('order_goods')->where('order_id', $order_id)->select();
                    $tarr = [];
                    foreach ($goods as $val) {
                        db::name('goods_specval')->where('specval_id', $val['goods_specval_id'])->setDec('stock', $val['num']);
                        if (!empty($val['supplier_id'])) {
                            $tarr[$val['supplier_id']]['money'] += $val['price']*$val['num'];
                        }
                    }

                    //创建供应商订单
                    foreach ($tarr as $k => $v) {
                        $re_supplier = Db::name('supplier_order')->insertGetId([
                            'order_id' => $info['order_id'],
                            'order_no' => $info['order_no'],
                            'create_time' => date('Y-m-d H:i:s'),
                            'order_money' => $v['money'],
                            'supplier_id' => $k,
                            'date' => date('Y-m-d')
                        ]);

                        if (!$re_supplier) {
                            Db::rollback();
                            $this->error('接单失败');
                        }
                    }

                    $data = [
                        'order_id' => $order_id,
                        'user_id' => $info['user_id'],
                        'act_time' => date('Y-m-d H:i:s'),
                        'op_uid' => $this->user['id'],
                        'op_uname' => $this->user['username'],
                        'order_status' => $order_status,
                        'bop_order_status' => $info['order_status']
                    ];
                    
                    $re = db::name('order_action')->insert($data);
                    if ($re === false) {
                        Db::rollback();
                        $this->error('接单失败');
                    }
                    Db::commit();
                    $this->success('接单成功');

                }
            } elseif ($keywords) {
                $where = ['order_no|receiver_name|receiver_mobile|receiver_pcd|receiver_address' => ['like','%'.$keywords.'%'],'order_status' => ['>',0]];//['order_no' => $keywords];
            } else {
                $where = ['order_status' => $order_status];
            }
        }
        
        $order = db()->table('sdzx_order')->alias('o')
        ->field('o.*,s.delivery_name')
        ->join('sdzx_shipping s', 'o.order_id = s.order_id', 'left')
        ->where($where)->order($sort)->paginate('', false, ['query'=>Request()->param()]);

        // $order = db('order')->where($where)->order('create_time desc')->paginate('',false,['query'=>Request()->param()]);
        foreach ($order as $k => $v) {
            $v['goods']=db('order_goods')->where('order_id', $v['order_id'])->select();
            $order->offsetSet($k, $v);
        }
       
        $this->assign('status', $order_status?:1000);
        $this->assign('list', $order);
        return $this->fetch();
    }
    
    // 退货
    public function refund()
    {
        if (request()->isPost()) {
            $data = request()->only('order_id,ids,nums,order_status,remark');
            $order = db('order')->where('order_id', $data['order_id'])->find();
            
            if ($data['ids']) {
                // $config = Config::get('wx');
                // $con = array_merge($config['pay'], $config['xcx']);
                // $con['notify_url'] = request()->domain().$con['notify_url'];
                // $WxpaySdk = new WxpaySdk($con);
                $time = date('Y-m-d H:i:s');

                //日志记录
                // Log::init(Config::get('log_refund'));

                Db::startTrans();

                $refund_goods = []; $all_id = []; $money=0; $_remark=null;
                foreach ($data['ids'] as $key => $val) {
                    if (empty($data['nums'][$key])) {
                        continue;
                    }
                    $order_goods = Db::name('order_goods')->where('order_goods_id', $val)->find();

                    $num = $order_goods['num'] - $data['nums'][$key];

                    $re_ogi = Db::name('order_goods')->where('order_goods_id', $val)->update(['num' => $num]);
                    if ($re_ogi===false) {
                        Db::rollback();
                        $this->error('退货失败');
                    }

                    $re_id = Db::name('order_goods_return')->where('order_goods_id', $val)->insertGetId([
                        'og_id'        => $val,
                        'order_id'     => $order['order_id'],
                        'order_no'     => $order['order_no'],
                        'goods_id'     => $order_goods['goods_id'],
                        'goods_name'   => $order_goods['goods_name'],
                        'specval_id'   => $order_goods['goods_specval_id'],
                        'rg_time'      => $time,
                        'rg_num'       => $data['nums'][$key],
                        'rg_remark'    => $data['remark'][$key],
                        'return_money' => $order_goods['price'],
                        'rg_status'    => ($order['order_status'] == 40)?1:0
                    ]);
                    if (!$re_ogi) {
                        Db::rollback();
                        $this->error('退货失败');
                    }

                    $all_id[] = $re_id;
                    $money += $data['nums'][$key]*$order_goods['price'];

                    $_remark .= "商品：（{$order_goods['brand_name']}）{$order_goods['goods_name']} 退货数量：{$data['nums'][$key]} 退货原因：{$data['remark'][$key]}||";
                }

                $re_order = Db::name('order')->where(['order_id'=>$order['order_id']])->setDec('order_money',$money);
                if ($re_order===false) {
                    Db::rollback();
                    $this->error('退货失败');
                }
                
                // 添加退款审核记录
                $re_audit = Db::name('order_refund_audit')->insertGetId([
                    'create_time' => $time,
                    'remark'      => $_remark,
                    'money'       => $money,
                    'order_id'    => $order['order_id'],
                    'audit_type'  => 1
                ]);
                if (!$re_audit) {
                    Db::rollback();
                    $this->error('退货失败');
                }

                $re_org = Db::name('order_goods_return')->where(['rg_id'=>['in',$all_id]])->update(['audit_id'=>$re_audit]);
                if ($re_org===false) {
                    Db::rollback();
                    $this->error('退货失败');
                }

                $re_act = db('order_action')->insert([
                    'order_id'         => $order['order_id'],
                    'user_id'          => $order['user_id'],
                    'act_time'         => $time,
                    'op_uid'           => $this->user['id'],
                    'op_uname'         => $this->user['username'],
                    'order_status'     => $data['order_status'],
                    'bop_order_status' => $data['order_status'],
                    'op_model'         => request()->module(),
                    'act_remark'       => '订单部分商品已退货，商品已支付金额将在3个工作日内退回||'.$_remark
                ]);
                if (!$re_act) {
                    Db::rollback();
                    $this->error('退货失败');
                }

                if ($order['order_status'] == 40) {
                    $info = db('shipping_refund')->where('order_id', $order['order_id'])->find();
                    if (!$info) {
                        $shipping = db('shipping')->where('order_id', $order['order_id'])->find();
                        $re_sr = Db::name ('shipping_refund')->insert([
                            'order_id'      => $order['order_id'],
                            'order_no'      => $order['order_no'],
                            'buyer_id'      => $order['user_id'],
                            'buyer_name'    => $order['user_name'],
                            'agent_id'      => $order['agent_id'],
                            'agent_name'    => $order['agent_name'],
                            'delivery_id'   => $shipping['delivery_id'],
                            'delivery_name' => $shipping['delivery_name'],
                            'create_time'   => $time
                        ]);
                        if (!$re_sr) {
                            Db::rollback();
                            $this->error('退货失败');
                        }
                    }
                }

                Db::commit();
                $this->success('操作成功');

                // 发起退款操作
                // $refund_param = [
                //     'transaction_id' => $order['pay_no'],
                //     'out_refund_no'  => 'th_'.implode('',$all_id),
                //     'total_fee'      => $order['pay_money']*100,
                //     'refund_fee'     => $money*100,
                //     'op_user_id'     => $con['mchid']
                // ];
                
                // $refund = $WxpaySdk->refund($refund_param);

                // Log::record('订单退货('.$data['order_id'].')-退货退款'.date('Y-m-d H:i:s'),'refund');
                // Log::record($refund_param,'refund');
                // Log::record($refund,'refund');

                // if ($refund['return_code'] === 'SUCCESS' && $refund['result_code'] === 'SUCCESS') {
                //     Db::name('order_goods_return')->where(['rg_id'=>['in',$all_id]])->update(['pay_status'=>1]);
                // }else{
                //     Db::name('order_goods_return')->where(['rg_id'=>['in',$all_id]])->update(['error'=>var_export($refund,true)]);
                // }
                
                // if ($order['order_status'] == 40) {
                //     $info = db('shipping_refund')->where('order_id', $order['order_id'])->find();
                //     if (!$info) {
                //         $shipping = db('shipping')->where('order_id', $order['order_id'])->find();
                //         db('shipping_refund')->insert([
                //             'order_id'      => $order['order_id'],
                //             'order_no'      => $order['order_no'],
                //             'buyer_id'      => $order['user_id'],
                //             'buyer_name'    => $order['user_name'],
                //             'agent_id'      => $order['agent_id'],
                //             'agent_name'    => $order['agent_name'],
                //             'delivery_id'   => $shipping['delivery_id'],
                //             'delivery_name' => $shipping['delivery_name'],
                //             'create_time'   => $time
                //         ]);
                //     }
                // }
                
                // $re = db('order_action')->insert([
                //     'order_id'         => $order['order_id'],
                //     'user_id'          => $order['user_id'],
                //     'act_time'         => $time,
                //     'op_uid'           => $this->user['id'],
                //     'op_uname'         => $this->user['username'],
                //     'order_status'     => $data['order_status'],
                //     'bop_order_status' => $data['order_status'],
                //     'op_model'         => request()->module(),
                //     'act_remark'       => '订单部分商品已退货，商品已支付金额将在3个工作日内退回||'.$_remark
                // ]);
                
                // if ($re!==false) {
                //     $this->success('操作成功', '');
                // }
            }
        } else {
            $order_id = request()->param('order_id');
            $order = db('order')->where('order_id', $order_id)->find();
            $order_goods = db('order_goods')->where('order_id', $order_id)->select();
            $this->assign('order_goods', $order_goods);
            return view('refund', $order);
        }
    }
    
    /* 取消 */
    function cancel()
    {
        $order_id = input('order_id');
        !$order_id && $this->error('取消失败');
        //日志记录
        Log::init(Config::get('log_refund'));

        $time = date('Y-m-d H:i:s');

        $info = db('order')->where('order_id', $order_id)->find();
        Db::startTrans();

        $res = Db::name('order')->update(['order_id' => $order_id,'order_status' => 10]);
        if ($res === false) {
            Db::rollback();
            $this->error('取消失败');
        }

        $action_data = [
            'order_id'         => $order_id,
            'user_id'          => $info['user_id'],
            'act_time'         => $time,
            'op_uid'           => $this->user['id'],
            'op_uname'         => $this->user['username'],
            'order_status'     => 10,
            'bop_order_status' => $info['order_status'],
            'act_remark'       => '您的订单已取消，订单已支付金额将在3个工作日内退回'
        ];
        Db::name('order_action')->insert($action_data);

        // 退款 查出订单所有改价记录
        $repay_money = 0; //补价的钱
        $repay_arr = [];
        $hasrefund_money = 0; //已经退了的钱
        $change_order = Db::name('order_change')->where(['order_id'=>$order_id])->select();
        foreach ($change_order as $k => $v) {
            if ($v['pay_status']==1) {
                if ($v['price']<0) {
                    $hasrefund_money = $hasrefund_money-$v['price'];
                }else{
                    $repay_arr[] = $v;
                    $repay_money += $v['price'];
                }
            }
        }

        //订单所有退货记录
        // $refund_goods = Db::field('og.price,ogr.rg_num')
        // ->table('sdzx_order_goods')->alias('og')
        // ->join('sdzx_order_goods_return ogr','og.order_goods_id=ogr.og_id')
        // ->where("ogr.order_id = {$order_id} and ogr.pay_status=1")
        // ->select();
        
        $refund_goods = Db::name('order_goods_return')
        ->where("order_id = {$order_id} and pay_status=1")
        ->select();

        foreach ($refund_goods as $key => $value) {
            $hasrefund_money += $value['return_money']*$value['rg_num'];
        }


        // 发起退款操作
        // $config = Config::get('wx');
        // $con = array_merge($config['pay'], $config['xcx']);
        // $con['notify_url'] = request()->domain().$con['notify_url'];

        $total = 0;$change_idarr = [];

        // 先退订单钱
        if ($hasrefund_money<$info['pay_money']) {
            $changeD = [
                'order_id'         => $order_id,
                'price'            => -1*($info['pay_money']-$hasrefund_money),
                'time'             => $time,
                'op_uid'           => $this->uid,
                'op_name'          => $this->user['name'],
                'op_model'         => request()->module(),
                'remark'           => '订单取消退款-订单',
                'order_status'     => 10,
                'bop_order_status' => $info['order_status']
            ];
            $re_oc1 = Db::name('order_change')->insertGetId($changeD);
            if (!$re_oc1) {
                Db::rollback();
                $this->error('操作失败');
            }

            $total = $info['pay_money']-$hasrefund_money;
            $change_idarr[] = $re_oc1;

            // $refund_param = [
            //     'transaction_id' => $info['pay_no'],
            //     'out_refund_no'  => $re_oc1.'_'.time(),
            //     'total_fee'      => $info['pay_money']*100,
            //     'refund_fee'     => ($info['pay_money']-$hasrefund_money)*100,
            //     'op_user_id'     => $con['mchid']
            // ];
            // $WxpaySdk = new WxpaySdk($con);
            // $refund = $WxpaySdk->refund($refund_param);

            //日志记录
            Log::record('订单取消('.$info['order_no'].'---'.$order_id.')-订单退款'.date('Y-m-d H:i:s'),'refund');
            Log::record('total='.$total,'refund');

            // if ($refund['return_code'] === 'SUCCESS' && $refund['result_code'] === 'SUCCESS') {
            //     Db::name('order_change')->where(['change_id'=>$re_oc1])->update(['pay_status'=>1]);
            // }else{
            //     Db::rollback();
            //     $this->error('操作失败','',$refund['return_msg']);
            // }
        }else{
             //日志记录
            Log::record('订单取消('.$info['order_no'].'---'.$order_id.')-订单退款'.date('Y-m-d H:i:s'),'refund');
            Log::record('订单钱已经退完，已退金额：'.$hasrefund_money.'订单金额：'.$info['pay_money'],'refund');
        }
        
        // 再退补价的钱  我上面钱都退了下面不能数据回滚了
        if ($repay_arr) {
            foreach ($repay_arr as $k => $v) {
                $changeD = [
                    'order_id'         => $order_id,
                    'pid'              => $v['change_id'],
                    'price'            => -1*$v['price'],
                    'time'             => $time,
                    'op_uid'           => $this->uid,
                    'op_name'          => $this->user['name'],
                    'op_model'         => request()->module(),
                    'remark'           => '订单取消退款-补价单',
                    'order_status'     => 10,
                    'bop_order_status' => $info['order_status']
                ];
                $re_oc2 = Db::name('order_change')->insertGetId($changeD);
                if (!$re_oc2) { 
                    Db::rollback();
                    $this->error('操作失败');
                }

                $total += $v['price'];
                $change_idarr[] = $re_oc2;
                // $refund_param2 = [
                //     'transaction_id' => $v['pay_no'],
                //     'out_refund_no'  => $re_oc2.'_'.time(),
                //     'total_fee'      => $v['pay_money']*100,
                //     'refund_fee'     => $v['price']*100,
                //     'op_user_id'     => $con['mchid']
                // ];
                // $WxpaySdk2 = new WxpaySdk($con);
                // $refund2 = $WxpaySdk2->refund($refund_param2);

                //日志记录
                Log::record('订单取消('.$info['order_no'].'---'.$order_id.')-补价退款'.date('Y-m-d H:i:s'),'refund');
                Log::record('price='.$v['price'],'refund');
                Log::record('total='.$total,'refund');
                // Log::record($refund2,'refund');

                // if ($refund2['return_code'] === 'SUCCESS' && $refund2['result_code'] === 'SUCCESS') {
                //     Db::name('order_change')->where(['change_id'=>$re_oc2])->update(['pay_status'=>1]);
                // }else{
                //     Db::name('order_change')->where(['change_id'=>$re_oc2])->update(['error'=>var_export($refund2,true)]);
                // }
            }
        }else{
             //日志记录
            // Log::record('订单取消('.$info['order_no'].'---'.$order_id.')-无补价记录'.date('Y-m-d H:i:s'),'refund');
        }

        //添加审核记录
        $re_audit = Db::name('order_refund_audit')->insertGetId([
            'create_time' => $time,
            'remark'      => '订单取消',
            'money'       => $total,
            'order_id'    => $order_id,
            'audit_type'  => 3
        ]);

        if (!$re_audit) {
            Db::rollback();
            $this->error('操作失败');
        }

        // 更新
        if ($change_idarr) {
            Db::name('order_change')->where(['change_id'=>['in',$change_idarr]])->update(['audit_id'=>$re_audit]);
        }

        Db::commit();
        $this->success('操作成功','refresh');
    }
    
    /* 确认收货 */
    public function receipt()
    {
        $order_id = request()->param('order_id');
        $order_status = request()->param('order_status');
        if ($order_id && $order_status) {
            $info = db('order')->where('order_id', $order_id)->find();
            $res =db('order')->update(['order_id' => $order_id,'order_status'  => $order_status]);
            if ($res !== false) {
                $data = [
                    'order_id' => $order_id,
                    'user_id' => $info['user_id'],
                    'act_time' => date('Y-m-d H:i:s'),
                    'op_uid' => $this->user['id'],
                    'op_uname' => $this->user['username'],
                    'order_status' => $order_status,
                    'bop_order_status' => $info['order_status']
                ];
                $re = db('order_action')->insert($data);
                if ($re !==false) {
                    $this->success('操作成功', 'refresh');
                }
            } else {
                $this->error('操作失败', 'refresh');
            }
        }
    }

    /*改价*/
    public function changePrice()
    {
        if (request()->isPost()) {
            $param = request()->param();

            $shop_price = $param['price'];
            $remarks    = $param['remark'];
            $order_id   = $param['orderID'];

            $info = db('order_change')->where('order_id', $order_id)->order('change_id desc')->find();

            if (isset($info['pay_status']) && $info['pay_status']==0) {
                $this->error('上次改价还未完成');
            }

            //日志记录
            // Log::init(Config::get('log_refund'));

            $old_order = db('order')->where('order_id', $order_id)->find();

            Db::startTrans();
            $goodsPrice = 0; $_remark = '';
            if (isset($param['goods']) && !empty($param['goods'])) { //商品改价
                foreach ($param['goods'] as $k => $v) {
                    if (!$v['specval_id']) {
                        continue;
                    }
                    $goods = Db::name('order_goods')->where(['order_id'=>$order_id,'goods_specval_id'=>$v['specval_id']])->find();
                    Db::name('order_goods')->where(['order_id'=>$order_id,'goods_specval_id'=>$v['specval_id']])->update(['price'=>$v['price']]);
                    $_price = $v['price']-$goods['price'];
                    
                    $diff = round ($goods['num']*$_price,2);
                    $goodsPrice += $diff;
                    if ($diff<0) {
                        $diff=-1*$diff;
                        $_remark .= "商品（{$goods['brand_name']}）{$goods['goods_name']}原价￥{$goods['price']}改为￥{$v['price']}，退款￥{$diff}元||";
                    }else{
                        $_remark .= "商品（{$goods['brand_name']}）{$goods['goods_name']}原价￥{$goods['price']}改为￥{$v['price']}，补款￥{$diff}元||";
                    }
                    
                }
            }

            $shop_price = strval($shop_price)+strval($goodsPrice);  //好奇葩的问题 strval()
            $remarks = $_remark.$remarks;

            if (($old_order['pay_money']+$shop_price)<=0) {
                $this->error('退款金额不能大于订单支付金额');
            }

            $time =date('Y-m-d H:i:s');
            $price = $old_order['order_money']+$shop_price;

            $action_data = [
                'user_id'          => $old_order['user_id'],
                'order_id'         => $order_id,
                'act_time'         => $time,
                'op_uid'           => $this->user['id'],
                'op_uname'         => $this->user['username'],
                'order_status'     => 25,
                'bop_order_status' => $old_order['order_status'],
                'op_model'         => request()->module()
            ];

            $data = [
                'order_id'         => $order_id,
                'price'            => $shop_price,
                'time'             => $time,
                'op_uid'           => $this->user['id'],
                'op_name'          => $this->user['username'],
                'op_model'         => request()->module(),
                'remark'           => $remarks,
                'bop_order_status' => $old_order['order_status'],
            ];


            
            if($shop_price>0){ //需要付款 则改变订单的状态 防止订单流程往下走
                $data['order_status'] = 25;
                $action_data['act_remark' ] = "您的订单金额已发生变化（￥{$old_order['order_money']}改为￥{$price}）,需补差价￥{$shop_price}元";
                if ($remarks) {
                    $action_data['act_remark' ] = $action_data['act_remark' ].'||'.$remarks;
                }
                $re_o = Db::name('order')->where('order_id', $order_id)->update([
                    'order_money' => $price,
                    'order_status' => 25,
                    'refund_money' => $shop_price,
                    'refund_money_total' => ['exp',"refund_money_total+$shop_price"],
                    'refund_time' => $time
                ]);
                if ($re_o===false) {
                    Db::rollback();
                    $this->error('操作失败');
                }
                $re_oc = Db::name('order_change')->insertGetId($data);
                if (!$re_oc) {
                    Db::rollback();
                    $this->error('操作失败');
                }
            }else{ //平台需要退钱 不修改订单的状态 订单流程可以往下走

                $action_data['order_status'] = $old_order['order_status'];
                $action_data['act_remark' ] = "您的订单金额已发生变化（￥{$old_order['order_money']}改为￥{$price}）,退款差额将在3个工作日内退回";
                if ($remarks) {
                    $action_data['act_remark' ] = $action_data['act_remark' ].'||'.$remarks;
                }
                $re_o = Db::name('order')->where('order_id', $order_id)->update([
                    'order_money' => $price,
                    'refund_money' => $shop_price,
                    'refund_money_total' => ['exp',"refund_money_total+$shop_price"],
                    'refund_time' => $time
                ]);
                if ($re_o===false) {
                    Db::rollback();
                    $this->error('操作失败');
                }

                $re_oc = Db::name('order_change')->insertGetId($data);
                if (!$re_oc) {
                    Db::rollback();
                    $this->error('操作失败');
                }

                // 添加退款审核记录
                $re_audit = Db::name('order_refund_audit')->insertGetId([
                    'create_time' => $time,
                    'remark'      => $remarks,
                    'money'       => $shop_price*-1,
                    'order_id'    => $order_id,
                    'audit_type'  => 2
                ]);
                if (!$re_audit) {
                    Db::rollback();
                    $this->error('退货失败');
                }
                
                Db::name('order_change')->where(['change_id'=>$re_oc])->update(['audit_id'=>$re_audit]);

                // 发起退款操作
                // $config = Config::get('wx');
                // $con = array_merge($config['pay'], $config['xcx']);
                // $con['notify_url'] = request()->domain().$con['notify_url'];
                // $WxpaySdk = new WxpaySdk($con);

                // $refund_param = [
                //     'transaction_id' => $old_order['pay_no'],
                //     'out_refund_no'  => $re_oc.'_'.time(),
                //     'total_fee'      => $old_order['pay_money']*100,
                //     'refund_fee'     => $shop_price*-100,
                //     'op_user_id'     => $con['mchid']
                // ];
                // $refund = $WxpaySdk->refund($refund_param);
                
                // Log::record('订单改价('.$order_id.')-改价退款'.date('Y-m-d H:i:s'),'refund');
                // Log::record($refund_param,'refund');
                // Log::record($refund,'refund');

                // if ($refund['return_code'] === 'SUCCESS' && $refund['result_code'] === 'SUCCESS') {
                //     Db::name('order_change')->where(['change_id'=>$re_oc])->update(['pay_status'=>1]);
                // }else{
                //     Db::rollback();
                //     $this->error('操作失败','',$refund['return_msg']);
                // }
            }

            Db::commit();

            db('order_action')->insert($action_data);
            $old_order['order_change_money'] = $price;
            $this->sendTmp($old_order);
            $this->success('操作成功', '');
        }else{
            $param = request()->param();
            !$param['order_id'] && $this->error('参数错误');
            $order = Db::name('order')->where(['order_id'=>$param['order_id']])->find();

            $goods = Db::name('order_goods')->where(['order_id'=>$param['order_id']])->select();
            return $this->fetch('',['order'=>$order,'goods'=>$goods]);
        }
    }
    /**
     * 发送模板消息
     * @param  [type] $order [description]
     * @return [type]        [description]
     */
    function sendTmp($order)
    {   
        $order['order_change_money'] = number_format($order['order_change_money'],2);
        $order['order_money'] = number_format($order['order_money'],2);

        import('Alidayu.TopSdk');
        import('Alidayu.top.TopClient');
        import('Alidayu.top.request.AlibabaAliqinFcSmsNumSendRequest');
        $appkey="23535194";
        $secret="48953173553ad6ad6b306138f518d7f1";


        $code=substr(str_shuffle("012345678901234567890123456789"), 0, 6);
        $product="速冻在线";

        $c = new \TopClient();
        $c ->appkey = $appkey ;
        $c ->secretKey = $secret ;
        $req = new \AlibabaAliqinFcSmsNumSendRequest();
        $req ->setExtend( "" );
        $req ->setSmsType( "normal" );
        $req ->setSmsFreeSignName( "速冻在线" );
        $req ->setSmsParam("{name:'".$order['receiver_name']."',order:'".$order['order_no']."',price1:'".$order['order_money']."',price2:'".$order['order_change_money']."' }");
        $req ->setRecNum( $order['receiver_mobile'] );
        $req ->setSmsTemplateCode( "SMS_99485038" );
        $re = $c ->execute( $req );
    }

    /**
     * 打印条码
     * @return [type] [description]
     */
    function webPrintcode(){
        $param = Request()->param();
        !$param['order_id'] && $this->error('参数错误');

        $goods = Db::name('order_goods')->where('order_id',$param['order_id'])->select();

        $order = Db::field('o.receiver_name,s.shop_name')
        ->table('sdzx_order')->alias('o')
        ->join('sdzx_shop s','o.user_id=s.user_id','left')
        ->where("o.order_id={$param['order_id']}")
        ->find();


        $data['list'] = $goods;
        $data['order'] = $order;
        return $this->fetch('',$data);
    }

    /* 订单详情 */
    public function details(){
        $order_id = request()->param('order_id');
        !$order_id && $this->error('参数错误');
        
        $order = db('order')->where('order_id',$order_id)->find();
        $order_change = db('order_change')->where('order_id',$order_id)->order('time asc')->select();
        $order_return = db('order_goods_return')->where('order_id',$order_id)->order('rg_time asc')->select();
        
        $order_change && $this->assign('order_change',$order_change);
        $order_return && $this->assign('order_return',$order_return);
        $this->assign('order',$order);
        return $this->fetch();
    }
	
	/* 修改订单状态 */
	function update(){
		$data['order_id'] = request()->param('order_id');
		$data['order_status'] = request()->param('order_status');
		
		if(empty($data['order_id']) || empty($data['order_status'])){
			$this->error('参数错误');
		}else{
			$res = db('order')->update($data);
			if($res !== false){
				$this->success('操作成功');
			}else{
				$this->error('操作失败');
			}
		}
	}
	
	/* 订单消息提醒 */
	public function remind(){
		$info = db('order')->where(['order_status' => 20, 'pay_status' => 1])->order('create_time desc')->find();
		if($info){
			$this->success('success','');
		}else{
			$this->error('error','');
		}
	}
}
